#!/bin/bash
#
# Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

readonly SCRIPTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly ROOT_DIR="$(dirname $SCRIPTS_DIR)"
readonly COVERAGE_OPTIONS="GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES -enableCodeCoverage YES"

# When run on Travis CI, this variable should be passed in
if [[ ! $DESTINATION ]]; then
  DESTINATION="platform=iOS Simulator,name=iPhone 7,OS=latest"
fi

# Given a path to an Xcode log file in $1, print a guess at what caused the
# failure.
function guess_failure() {
  if [[ $TRAVIS == "true" ]]; then
    tail -n 200 "$1"
  else
    grep --context=20 "The following build commands failed:" "$1"
  fi
}

xcodebuid_test() {
  if hash xcpretty 2>/dev/null; then
    set -o pipefail # Required for xcpretty to propagate failure.
    xcodebuild test "${@:1}" "$COVERAGE_OPTIONS" -destination "$DESTINATION" | xcpretty
  else
    xcodebuild test "${@:1}" "$COVERAGE_OPTIONS" -destination "$DESTINATION"
  fi
}

if [ ! -d "$ROOT_DIR/catalog/MDCCatalog.xcworkspace" ]; then
  pod install --project-directory="$ROOT_DIR/catalog"
fi

did_any_fail=false

xcodebuid_test \
  -workspace "$ROOT_DIR/catalog/MDCCatalog.xcworkspace" \
  -scheme "MDCCatalog"
if [ $? -ne 0 ]; then
  did_any_fail=true
fi

if $did_any_fail; then
  exit 1
fi